<template>
  <div class="energy-storage-layout">
    <!-- 第一大块 - 4个子块 -->
    <div class="top-section">
      <div class="stats-container">
        <div v-for="(item, index) in topStats" :key="index" class="stat-card" :class="`bg-${index % 4 + 1}`">
          <div class="stat-content">
            <div class="stat-icon">
              <img style="width: 100%;height: 100%" :src="item.icon" :alt="item.title + '图标'"
                   @error="handleIconError"/>
            </div>
            <div class="stat-text">
              <div class="stat-title">{{ item.title }}</div>
              <div class="stat-value">{{ item.value + item.unit }}</div>
              <div class="stat-unit">{{ }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 第二大块 - 子tab和内容 -->
    <div class="bottom-section">
      <el-tabs v-model="activeSubTab" class="sub-tabs">
        <el-tab-pane label="全部" name="all">
          <DeviceGrid :devices="filteredDevices('all')"/>
        </el-tab-pane>
        <el-tab-pane label="正常" name="normal">
          <DeviceGrid :devices="filteredDevices('normal')"/>
        </el-tab-pane>
        <el-tab-pane label="异常" name="abnormal">
          <DeviceGrid :devices="filteredDevices('abnormal')"/>
        </el-tab-pane>
        <el-tab-pane label="离线" name="offline">
          <DeviceGrid :devices="filteredDevices('offline')"/>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, watch} from 'vue'
import DeviceGrid from './DeviceGrid.vue'

const props = defineProps({
  type: {
    type: String,
    required: true,
    validator: (value) => ['independent', 'commercial', 'district'].includes(value)
  },
  region: {
    type: Array,
    default: () => []
  }
})

const activeSubTab = ref('all')

// 1. 在脚本中定义获取图标路径的函数（使用 Vite 支持的 import.meta.url）
const getIconUrl = (iconName) => {
  try {
    // 正确用法：在脚本中处理路径，Vite 会自动解析
    return new URL(`/src/assets/operation-monitoring/${iconName}`, import.meta.url).href
  } catch (error) {
    console.warn(`图标 ${iconName} 加载失败，使用默认图标`, error)
    // 加载失败时返回默认图标
    return new URL('/src/assets/operation-monitoring/default.png', import.meta.url).href
  }
}

// 模拟数据 - 根据类型返回不同的统计数据
const topStats = computed(() => {
  const statsMap = {
    independent: [
      {icon: getIconUrl('实时功率.png'), title: '场站总数', value: '1', unit: '座'},
      {icon: getIconUrl('今日充电量.png'), title: '装机功率/容量', value: '890', unit: 'MWh'},
      {icon: getIconUrl('今日放电量.png'), title: '今日充/放电量', value: '18,500', unit: 'KWh'},
      {icon: getIconUrl('充放电效率.png'), title: '今日充放电收益', value: '92.5', unit: '元'}
    ],
    commercial: [
      {icon: getIconUrl('实时功率.png'), title: '场站总数', value: '2', unit: '座'},
      {icon: getIconUrl('今日充电量.png'), title: '装机功率/容量', value: '890', unit: 'MWh'},
      {icon: getIconUrl('今日放电量.png'), title: '今日充/放电量', value: '18,500', unit: 'KWh'},
      {icon: getIconUrl('充放电效率.png'), title: '今日充放电收益', value: '92.5', unit: '元'}
    ],
    district: [
      {icon: getIconUrl('实时功率.png'), title: '场站总数', value: '3', unit: '座'},
      {icon: getIconUrl('今日充电量.png'), title: '装机功率/容量', value: '890', unit: 'MWh'},
      {icon: getIconUrl('今日放电量.png'), title: '今日充/放电量', value: '18,500', unit: 'KWh'},
      {icon: getIconUrl('充放电效率.png'), title: '今日充放电收益', value: '92.5', unit: '元'}
    ]
  }

  return statsMap[props.type]
})

// 模拟设备数据
const allDevices = computed(() => {
  const devices = []
  const prefixMap = {
    independent: '储能小车',
    commercial: '工商业储能',
    district: '台区储能'
  }

  for (let i = 1; i <= 3; i++) {
    const status = i % 4 === 0 ? 'offline' : i % 6 === 0 ? 'abnormal' : 'normal'
    devices.push({
      id: `${props.type}-${i}`,
      showChart: i % 3 === 0?true:false,
      icon: getIconUrl('电站logo.png'),
      name: `${prefixMap[props.type]}设备${i}`,
      Label: [{name: '实时功率', value: '73', unit: 'MW'}, {
        name: '日充电量',
        value: '12',
        unit: 'MWH'
      }, {name: '日放电量', value: '730', unit: 'MWH'}, {name: 'SOC', value: '12', unit: '%'}],
      status: status,
      power: Math.floor(Math.random() * 500) + 100,
      capacity: Math.floor(Math.random() * 200) + 50,
      efficiency: (Math.random() * 20 + 80).toFixed(1)
    })
  }
  return devices
})

const filteredDevices = computed(() => (filterType) => {
  const devices = filterType === 'all' ? allDevices.value : allDevices.value.filter(device => device.status === filterType)
  console.log(`${props.type}储能 - ${filterType}设备数量:`, devices.length)
  return devices
})

// 监听地区变化
watch(() => props.region, (newRegion) => {
  console.log(`${props.type}储能 - 地区变化:`, newRegion)
  // 这里可以根据地区变化重新加载数据
}, {deep: true})

// 图标加载错误处理
const handleIconError = (event) => {
  console.warn('图标加载失败:', event.target.src)
  // 可以设置一个默认图标或者隐藏图标
  event.target.style.display = 'none'
}
</script>

<style scoped>
/* 预定义不同背景色的类 */
.bg-1 {
  background-color: #F5F6FF;
}

.bg-2 {
  background-color: #F7FFF5;
}

.bg-3 {
  background-color: #FFF9F5;
}

.bg-4 {
  background-color: #F5F9FF;
}

.energy-storage-layout {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.top-section {
  flex-shrink: 0;
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 140px;
  box-sizing: border-box;
}

.stats-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
  height: 100%; /* 确保容器高度占满父元素 */
}

.stat-card {
  flex: 1;
  min-width: 200px;
  max-width: 372px;
  height: 99px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #303133; /* 深色文字，适应浅色背景 */
  box-shadow: 0 4px 15px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 12px;
  width: 100%;
  height: 100%;
}

.stat-text {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.stat-icon {
  margin-left: 20px;
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-icon img {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

.stat-title {
  font-size: 14px;
  color: #606266; /* 中等深度的灰色，适合标题 */
  margin-bottom: 4px;
  font-weight: 500;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 2px;
  color: #303133; /* 深色文字，重要数值 */
}

.stat-unit {
  font-size: 12px;
  color: #909399; /* 较浅的灰色，适合单位 */
}

.bottom-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: visible; /* 允许子组件滚动 */
  box-sizing: border-box;
}

.sub-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

:deep(.el-tabs__content) {
  flex: 1;
  overflow: visible; /* 允许子组件滚动 */
  display: flex;
  flex-direction: column;
}

@media (max-width: 768px) {
  .stats-container {
    flex-direction: column;
  }

  .stat-card {
    width: 100%;
    max-width: none;
  }
}
</style>